package kr.saeildamil.androidforstudy2.ch33;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import kr.saeildamil.androidforstudy2.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;

public class AttachImage extends Activity {
	static final int CALL_CAMERA = 0;
	static final int CALL_CAMERA2 = 1;
	static final int CALL_GALLARY = 2;
	
	ImageView mImage;
	String mPath;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch33_attachimage);
	
		mImage = (ImageView) findViewById(R.id.attachimage);
		mPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/attachimage.jpg";
		
	}
	
	public void mOnClick(View v){
		Intent intent = new Intent();
		int requestCode = 0;
		switch (v.getId()) {
		case R.id.btncamera:
			intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
			requestCode = CALL_CAMERA;
			break;
		case R.id.btncamera2:
			intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPath)));
			requestCode = CALL_CAMERA2;
			break;
		case R.id.btngallery:
			intent.setAction(Intent.ACTION_PICK);
			intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			requestCode = CALL_GALLARY;
			break;
		}
		startActivityForResult(intent, requestCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case CALL_CAMERA:
				mImage.setImageBitmap((Bitmap)data.getExtras().get("data"));
				break;
			case CALL_CAMERA2:
				mImage.setImageBitmap(BitmapFactory.decodeFile(mPath));
				break;
			case CALL_GALLARY:
				try {
					mImage.setImageBitmap(MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			}
		}
	}
}
